package services

import (
	"context"
	"errors"
	"wxapi/internal/svc"
	"wxapi/models"

	"gitee.com/dromara/carbon/v2"
)

func GetCarGoods(ctx context.Context, svc *svc.ServiceContext, userId int64) ([]*models.UserCar, error) {
	cars := make([]*models.UserCar, 0)
	svc.Mysql.Model(&models.UserCar{}).Preload("Doctor").Preload("Doctor.SellPoint").Preload("Doctor.Level").Preload("Skill.Skill").Where("user_id = ? AND begin_time >= ?", userId, carbon.Now().ToDateTimeString()).Find(&cars)
	return cars, nil
}

func AddCarGoods(ctx context.Context, svc *svc.ServiceContext, userId, DoctorId, ItemId int64, beginTime carbon.Carbon) error {
	item := &models.DoctorSkill{}
	svc.Mysql.Where("id = ? AND doctor_id = ? AND state = 100", ItemId, DoctorId).Find(item)
	if item.ID == 0 {
		return errors.New("项目不存在")
	}

	doctor := &models.Doctor{}
	svc.Mysql.Where("id = ? AND state = 100", DoctorId).Find(doctor)
	if doctor.ID == 0 {
		return errors.New("医生不存在")
	}
	car := &models.UserCar{
		UserId:    userId,
		StoreId:   doctor.StoreId,
		DoctorId:  DoctorId,
		SkillId:   ItemId,
		BeginTime: beginTime,
		Duration:  item.Duration,
		Count:     1,
		Price:     item.Price,
	}
	svc.Mysql.Create(car)
	return nil
}

func RemoveCarGoods(ctx context.Context, svc *svc.ServiceContext, userId, carId int64) error {
	car := &models.UserCar{}
	svc.Mysql.Where("user_id = ? AND id = ?", userId, carId).Find(car)
	if car.ID == 0 {
		return errors.New("购物车不存在")
	}
	svc.Mysql.Delete(car)
	return nil
}

func ClearCar(ctx context.Context, svc *svc.ServiceContext, userId int64) error {
	svc.Mysql.Where("user_id = ?", userId).Delete(&models.UserCar{})
	return nil
}
